package cn.tedu.antcolony.market.controller;


import cn.tedu.antcolony.market.pojo.param.ClueAddNewParam;
import cn.tedu.antcolony.market.pojo.param.ClueUpdateInfoParam;
import cn.tedu.antcolony.market.pojo.vo.ClueListItemVO;
import cn.tedu.antcolony.market.pojo.vo.ClueStandardVO;
import cn.tedu.antcolony.market.service.IClueService;
import cn.tedu.antcolonycommons.pojo.vo.PageData;
import cn.tedu.antcolonycommons.web.JsonResult;
import cn.tedu.antconlonysever.contract.pojo.param.CustomerAddNewParam;
import cn.tedu.antconlonysever.contract.pojo.param.LinkmanAddNewParam;
import cn.tedu.antconlonysever.contract.service.impl.CustomerServiceImpl;
import cn.tedu.antconlonysever.contract.service.impl.LinkmanServiceImpl;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

@RestController
//采用Restful风格请求处理类
@Api(tags = "04. 线索管理模块")
@Slf4j
@Validated
//@Validated用于校验参数
public class ClueController {

    @Autowired
    private IClueService clueService;

    public ClueController() {
        log.debug("创建控制器类对象：ClueController");
    }

    // http://localhost:8887/clue/add-new
    @PostMapping("/clue/add-new")
    @PreAuthorize("hasAuthority('/market/clue/add-new')")
    @ApiOperation("添加线索")
    @ApiOperationSupport(order = 100)
    public JsonResult<Void> addNew(@Valid ClueAddNewParam clueAddNewParam) {
        log.debug("开始处理【添加线索】的请求，参数：{}", clueAddNewParam);
        clueService.addNew(clueAddNewParam);
        return JsonResult.ok();
    }

    // http://localhost:8887/clue/123/delete
    @PostMapping("/clue/{id:[0-9]+}/delete")
    @PreAuthorize("hasAuthority('/market/clue/delete')")
    @ApiOperation("根据ID删除线索")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    //@PathVariable获取请求路径里的动态参数
    public JsonResult<Void> delete1(
            @PathVariable @Range(min = 1, message = "请提交有效的线索ID值！") Long id) {
        log.debug("开始处理【根据ID删除线索】的请求，参数：{}", id);
        clueService.delete1(id);
        return JsonResult.ok();
    }

    // http://localhost:8887/clue/deleteBatch
    @PostMapping("/clue/deleteBatch/{id:[0-9]+}")
    @PreAuthorize("hasAuthority('/market/clue/delete')")
    @ApiOperation("根据IDs删除线索")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    //@PathVariable获取请求路径里的动态参数
    public JsonResult<Void> deleteBatch(
            @PathVariable @Range(min = 1, message = "请提交有效的线索ID值！") List<String> id) {
        log.debug("开始处理【根据ID删除线索】的请求，参数：{}", id);
        try{
            for (String ids:id){
                System.out.println(ids);
            }
            clueService.deleteBatch(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        return JsonResult.ok();
    }

    @PostMapping("/customersea/{id:[0-9]+}/delete")
    @PreAuthorize("hasAuthority('/market/clue/delete')")
    @ApiOperation("根据ID删除客户公海")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "客户公海ID", required = true, dataType = "long")
    })
    //@PathVariable获取请求路径里的动态参数
    public JsonResult<Void> delete2(
            @PathVariable @Range(min = 1, message = "请提交有效的公海ID值！") Long id) {
        log.debug("开始处理【根据ID删除公海】的请求，参数：{}", id);
        clueService.delete2(id);
        return JsonResult.ok();
    }


    // http://localhost:8887/clue/123/update
    @PostMapping("/clue/{id:[0-9]+}/update")
    @PreAuthorize("hasAuthority('/market/clue/update')")
    @ApiOperation("修改线索详情")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    public JsonResult<Void> updateInfoById1(@PathVariable @Range(min = 1, message = "请提交有效的线索ID值！") Long id,
                                            @Valid ClueUpdateInfoParam clueUpdateInfoParam) {
        log.debug("开始处理【修改线索详情】的请求，ID：{}，新数据：{}", id, clueUpdateInfoParam);
        clueService.updateInfoById1(id, clueUpdateInfoParam);
        return JsonResult.ok();
    }

    // http://localhost:8887/customersea/123/update
    @PostMapping("/customersea/{id:[0-9]+}/update")
    @PreAuthorize("hasAuthority('/market/clue/update')")
    @ApiOperation("修改公海详情")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公海ID", required = true, dataType = "long")
    })
    public JsonResult<Void> updateInfoById2(@PathVariable @Range(min = 1, message = "请提交有效的公海ID值！") Long id,
                                            @Valid ClueUpdateInfoParam clueUpdateInfoParam) {
        log.debug("开始处理【修改公海详情】的请求，ID：{}，新数据：{}", id, clueUpdateInfoParam);
        clueService.updateInfoById2(id, clueUpdateInfoParam);
        return JsonResult.ok();
    }

    // http://localhost:8887/clue/123/transform
    @PostMapping("/clue/{id:[0-9]+}/transfer")
    @PreAuthorize("hasAuthority('/market/clue/add-new')")
    @ApiOperation("根据ID转让线索")
    @ApiOperationSupport(order = 400)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    public JsonResult<Void> transferClue(
            @PathVariable @Range(min = 1, message = "请提交合法的线索ID值！") Long id, String name) {
        log.debug("开始处理【根据ID转让线索】的请求，参数：{},转让人{}", id, name);
        clueService.transferClue(id, name);
        return JsonResult.ok();
    }

    // http://localhost:8887/clue/123/transform
    @PostMapping("/clue/{id:[0-9]+}/transform")
    @PreAuthorize("hasAuthority('/market/clue/add-new')")
    @ApiOperation("根据ID转入公海")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    public JsonResult<Void> transform(
            @PathVariable @Range(min = 1, message = "请提交合法的线索ID值！") Long id) {
        log.debug("开始处理【根据ID转入公海】的请求，参数：{}", id);
        clueService.transform(id);
        return JsonResult.ok();
    }


    // http://localhost:8887/clue/123/pickup
    @PostMapping("/customersea/{id:[0-9]+}/{name}/pickup")
    @PreAuthorize("hasAuthority('/market/clue/add-new')")
    @ApiOperation("根据ID领取公海")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公海ID", required = true, dataType = "long")
    })
    public JsonResult<Void> pickup(
            @PathVariable @Range(min = 1, message = "请提交合法的公海ID值！") Long id, @PathVariable String name) {
        log.debug("开始处理【根据ID领取公海】的请求，参数：{}", id);
        clueService.pickCustomerSea(id, name);
        return JsonResult.ok();
    }

    // http://localhost:8887/clue/123/pickup
    @PostMapping("/customersea/{id:[0-9]+}/transfer")
    @PreAuthorize("hasAuthority('/market/clue/add-new')")
    @ApiOperation("根据ID将线索转成客户")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    public JsonResult<Void> newCustomer(
            @PathVariable @Range(min = 1, message = "请提交合法的线索ID值！") Long id) {

        CustomerServiceImpl customerService = new CustomerServiceImpl();
        LinkmanServiceImpl linkmanService = new LinkmanServiceImpl();
        log.debug("开始处理【根据ID将线索转成客户】的请求，参数：{}", id);
        ClueStandardVO clueStandardVO = clueService.getStandardByClueId(id);

        CustomerAddNewParam customerAddNewParam = new CustomerAddNewParam();
        BeanUtils.copyProperties(clueStandardVO, customerAddNewParam);
        customerService.addNew(customerAddNewParam);

        LinkmanAddNewParam linkmanAddNewParam = new LinkmanAddNewParam();
        BeanUtils.copyProperties(clueStandardVO, linkmanAddNewParam);
        linkmanAddNewParam.setCusId(id);
        linkmanService.addNew(linkmanAddNewParam);

        clueService.delete1(id);

        return JsonResult.ok();
    }


    // http://localhost:8887/clue/123
    @GetMapping("/clue/{id:[0-9]+}")
    @PreAuthorize("hasAuthority('/market/clue/read')")
    @ApiOperation("根据ID查询线索详情")
    @ApiOperationSupport(order = 430)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "线索ID", required = true, dataType = "long")
    })
    public JsonResult<ClueStandardVO> getStandardById(
            @PathVariable @Range(min = 1, message = "请提交合法的线索ID值！") Long id) {
        log.debug("开始处理【根据ID查询线索详情】的请求，参数：{}", id);
        ClueStandardVO result = clueService.getStandardByClueId(id);
        return JsonResult.ok(result);
    }


    // http://localhost:8887/clue/123
    @GetMapping("/customersea/{id:[0-9]+}")
    @PreAuthorize("hasAuthority('/market/clue/read')")
    @ApiOperation("根据ID查询公海详情")
    @ApiOperationSupport(order = 440)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公海ID", required = true, dataType = "long")
    })
    public JsonResult<ClueStandardVO> getStandardById2(
            @PathVariable @Range(min = 1, message = "请提交合法的公海ID值！") Long id) {
        log.debug("开始处理【根据ID查询公海详情】的请求，参数：{}", id);
        ClueStandardVO result = clueService.getStandardByCustomerSeaId(id);
        return JsonResult.ok(result);
    }

    // http://localhost:9080/clue
    @GetMapping("/clue")
    @PreAuthorize("hasAuthority('/market/clue/read')")
    @ApiOperation("查询线索列表")
    @ApiOperationSupport(order = 450)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "queryType", value = "查询类型", example = "all")
    })
    public JsonResult<PageData<ClueListItemVO>> list(@Range(min = 1, message = "请提交有效的页码值！") Integer page,
                                                     String queryType) {
        log.debug("开始处理【查询线索列表】的请求，页码：{}", page);
        Integer pageNum = page == null ? 1 : page;
        PageData<ClueListItemVO> pageData;
        if ("all".equals(queryType)) {
            pageData = clueService.list1(pageNum, Integer.MAX_VALUE);
        } else {
            pageData = clueService.list1(pageNum);
        }
        return JsonResult.ok(pageData);
    }

    // http://localhost:9080/customersea
    @GetMapping("/customersea")
    @PreAuthorize("hasAuthority('/market/clue/read')")
    @ApiOperation("查询公海列表")
    @ApiOperationSupport(order = 460)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "queryType", value = "查询类型", example = "all")
    })
    public JsonResult<PageData<ClueListItemVO>> list2(@Range(min = 1, message = "请提交有效的页码值！") Integer page,
                                                      String queryType) {
        log.debug("开始处理【查询公海列表】的请求，页码：{}", page);
        Integer pageNum = page == null ? 1 : page;
        PageData<ClueListItemVO> pageData;
        if ("all".equals(queryType)) {
            pageData = clueService.list2(pageNum, Integer.MAX_VALUE);
        } else {
            pageData = clueService.list2(pageNum);
        }
        return JsonResult.ok(pageData);
    }


    // http://localhost:9080/clue/rebuild-cache
    @PostMapping("/clue/rebuild-cache")
    @PreAuthorize("hasAuthority('/market/clue/read')")
    @ApiOperation("重建线索缓存")
    @ApiOperationSupport(order = 900)
    public JsonResult<Void> rebuildCache() {
        log.debug("开始处理【重建线索缓存】的请求，无参数");
        clueService.rebuildCache();
        return JsonResult.ok();
    }
}